import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row, Col, Card, Icon, Tooltip, Form, Button, Input, Spin,
  Table, message, InputNumber, Statistic, Modal, Drawer, Progress,
} from 'antd';
import styles from './index.less';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter';
import tableDataCheck from '@/utils/isBackPrevPage';

const Search = Input.Search;
const FormItem = Form.Item;
class ProblemRecommendedList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      login: false,
      totala: 0,
      page: 1,
      pageSize: 10,
      similarList: [],
      query: '', // 搜索的关键词
      minWordCount: '', // 最小字数
      maxWordCount: '', // 最大字数
      minAskCount: '', // 最小询问次数
      maxAskCount: '', // 最大询问次数
      order: 'questionCount', // 排序字段
      sort: 'desc', //  排序方式，asc：升序，desc：降序,
      dxList: [],
      selectedRowKeys: [],
      rightAlist: [],
      rightBlist: [],
      successA: 'success',
      rightCol1: false,
      loginpig: false,
      num: 0,
      DrawerNoLogin: false,
      percent: 0,
      taskId: '',
    };
  }

  componentDidMount() {
    this.knowledgeQuestionList();
    this.maintainRecommendStatus();
    // this.knowledgeRecommendInfo()
  }

  recommendF1 = () => {
    this.setState({ rightCol1: true });
  };

  rightCol1 = () => {
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    this.props.form.validateFields((err, values) => {
      // 校验方法
      let a = '';
      let b = '';
      let c = '';
      let d = '';
      if (userInfo.InputNumber1 !== '') {
        a = Number(userInfo.InputNumber1);
      };
      if (userInfo.InputNumber2 !== '') {
        b = Number(userInfo.InputNumber2);
      };
      if (userInfo.xwcs1 !== '') {
        c = Number(userInfo.xwcs1);
      };
      if (userInfo.xwcs2 !== '') {
        d = Number(userInfo.xwcs2);
      };
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'knowledgeSmartMaintenance/knowledgerecommendSubmit',
          payload: {
            includeKey: userInfo.bkKeyword,
            notIncludeKey: userInfo.NoKeyword,
            minWordCount: a,
            maxWordCount: b,
            minAskCount: c,
            maxAskCount: d,
          },
          callback: res => {
            console.log(res);
            if (res.code === 0) {
              message.success(res.msg);
              this.time(); // 随时关闭
              this.setState({ loginpig: true });
              this.setState({ rightCol1: false });
            }
          },
        });
      });
    });
  };

  time = () => {
    setTimeout(() => {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'knowledgeSmartMaintenance/maintainRecommendStatus',
          payload: {},
          callback: res => {
            if (res.status === 'wait') {
              this.setState({ loginpig: true, taskId: res.taskId });
              // this.time()
              this.percent();
            } else {
              this.setState({ loginpig: false });
              this.knowledgeQuestionList();
              this.maintainRecommendStatus();
              // this.knowledgeRecommendInfo();
            };
            this.setState({ successA: res.status, rightAlist: res });
          },
        });
      });
    }, 1000);
  };

  rightColNo1 = () => {
    this.setState({ rightCol1: false });
  };

  // 进度条任务
  percent = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgerecommendProcess',
        payload: { taskId: this.state.taskId },
        callback: res => {
          if (res.process === '1.0') {
            this.setState({ num: res.process }, () => {
              this.time();
            });
          } else if (res.process === 0) {
            this.setState({ percent: res.process }, () => {
              setTimeout(() => {
                this.percent();
              }, 1000);
            });
          } else {
            const number = res.process;
            this.setState({ percent: Math.floor(Number(number * 100)) }, () => {
              setTimeout(() => {
                this.percent();
              }, 1000);
            });
          }
        },
      });
    });
  };

  // 获取问题推荐状态
  maintainRecommendStatus = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/maintainRecommendStatus',
        payload: {},
        callback: res => {
          if (res.status === 'wait') {
            this.setState({ loginpig: true, taskId: res.taskId }, () => {
              this.time();
            });
          };
          this.setState({ successA: res.status, rightAlist: res });
        },
      });
    });
  };

  // 获取问题推荐信息
  knowledgeRecommendInfo = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendInfo',
        payload: {},
        callback: res => {
          this.setState({ rightBlist: res });
        },
      });
    });
  };

  knowledgeQuestionList = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { page, pageSize, query, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendList',
        payload: { query, order, sort, current: page, size: pageSize },
        callback: res => {
          this.setState({
            similarList: res ? res.records : [],
            totala: res ? Number(res.total) : 0,
            login: false,
          });
        },
      });
    });
  };

  pageWay = a => {
    this.setState({ page: a }, () => {
      this.knowledgeQuestionList();
    });
  };

  onShowSizepageWay = (a, b) => {
    this.setState({ page: a, pageSize: b }, () => {
      this.knowledgeQuestionList();
    });
  };

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
  };

  // 批量删除 忽略回调
  knowledgeQuestionDelete = (ids, url) => {
    if (ids.length === 0) {
      message.error('请先选择需要操作内容');
    } else {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: url,
          payload: { ids },
          callback: res => {
            message.success(`${res.msg}`);
            //判断是否需要加载上一页数据 2022.4.8
            const { similarList, page } = this.state;
            const newCurrent = tableDataCheck(similarList, page, ids)
            this.setState(
              {
                login: false,
                selectedRowKeys: [],
                dxList: [],
                page: newCurrent
              },
              () => {
                this.knowledgeQuestionList();
                this.maintainRecommendStatus();
                // this.knowledgeRecommendInfo();
              }
            );
          },
        });
      });
    }
  };

  deleteTable = item => {
    this.setState({ login: true });
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/knowledgeRecommendIgnore');
  };

  deleteTables = item => {
    this.setState({ login: true });
    this.knowledgeQuestionDelete(Array(item.id), 'knowledgeSmartMaintenance/knowledgeRecommendIgnores');
  };

  handleOpen = item => { };

  // 批量删除
  batchDelete = () => {
    const { dxList } = this.state;
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeRecommendIgnore');
  };

  // 批量忽略
  moveBlacklist = () => {
    const { dxList } = this.state;
    this.knowledgeQuestionDelete(dxList, 'knowledgeSmartMaintenance/knowledgeRecommendIgnores');
  };

  // 查看
  view = (item, indexs) => {
    const { order, sort, page, pageSize, query } = this.state;
    let index = (page - 1) * pageSize + indexs;
    let items = item;
    items.order = order;
    items.sort = sort;
    items.index = index;
    items.query = query;
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/capacity/knowledgeSmartMaintenance/recommendedTreatment',
        params: { item: items },
        query: {
          item: JSON.stringify(items),
        },
      })
    );
  };

  // 排序
  pXhandleChange = (pagination, filters, sorter) => {
    if (sorter.field) { } else {
      this.setState({ order: 'questionCount', sort: 'desc' }, () => {
        this.knowledgeQuestionList();
      });
    };
    if (sorter.field === 'questionCount') {
      // 字数排序
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'questionCount', sort: 'asc' }, () => {
          this.knowledgeQuestionList();
        });
      };
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'questionCount', sort: 'desc' }, () => {
          this.knowledgeQuestionList();
        });
      }
    };
    if (sorter.field === 'askCount') {
      // 询问次数排序
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'askCount', sort: 'asc' }, () => {
          this.knowledgeQuestionList();
        });
      };
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'askCount', sort: 'desc' }, () => {
          this.knowledgeQuestionList();
        });
      }
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        // 文字
        xs: 24,
        sm: 5,
      },
      wrapperCol: {
        // 输入框
        xs: 24,
        sm: 19,
      },
    };
    const { selectedRowKeys, rightAlist } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        let a = [];
        selectedRows.map((item, index) => {
          a.push(item.id);
        });
        this.setState({ dxList: a, selectedRowKeys });
      },
    };
    const columns = [
      {
        title: '知识点标准问',
        width: 'calc(30vw)',
        dataIndex: 'std',
        render(item) {
          return <div dangerouslySetInnerHTML={{ __html: item }} />;
        },
      },
      {
        title: '推荐问题数量',
        width: 'calc(10vw)',
        sorter: (a, b) => { },
        dataIndex: 'questionCount',
      },
      {
        title: '询问总次数',
        dataIndex: 'askCount',
        sorter: (a, b) => { },
        width: 'calc(10vw)',
      },
      {
        title: '操作',
        width: 'calc(15vw)',
        render: (text, item, index) => {
          return (
            <div className={styles.flexBj}>
              <div
                style={{ marginRight: 10, marginBottom: 4 }}
                className={styles.buttongl}
                onClick={() => this.deleteTable(item)}
              >
                <span>
                  <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                </span>
                <span>删除</span>
              </div>

              <div
                style={{ marginRight: 10, marginBottom: 4 }}
                className={styles.buttong3}
                onClick={() => this.deleteTables(item)}
              >
                <span>
                  <Icon size="small" type="eye-invisible" style={{ marginRight: 5 }} />
                </span>
                <span>忽略</span>
              </div>

              <div
                style={{ marginRight: 10, marginBottom: 4 }}
                className={styles.buttong4}
                onClick={() => this.view(item, index)}
              >
                <span>
                  <Icon size="small" type="eye" style={{ marginRight: 5 }} />
                </span>
                <span>查看</span>
              </div>
            </div>
          );
        },
      },
    ];

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10 }} xs={24}>
                <div className={styles.title}>
                  <span>问题推荐</span>
                  <BackRouter pathname="/capacity/knowledgeSmartMaintenance"></BackRouter>
                </div>
              </Col>
            </Row>
            <Card bordered={false}>
              {this.state.loginpig ? (
                <div
                  className={styles.progrees}
                  style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}
                >
                  <div style={{ color: '#000' }}>问题推荐中,请稍后再来查看...</div>
                  <div style={{ height: 30 }}></div>
                  <Progress type="circle" percent={this.state.percent} width={90} strokeWidth={8} />
                  <div style={{ height: 30 }}></div>
                </div>
              ) : (
                <Row>
                  <Row style={{ margin: '10px 0px 40px 0px' }} gutter={100}>
                    <Col span={5}>
                      <Statistic title="推荐知识点数量" value={this.state.rightAlist.groupCount} />
                    </Col>
                    <Col span={5}>
                      <Statistic title="推荐问题数量" value={this.state.rightAlist.questionCount} />
                    </Col>
                    <Col span={5}>
                      <Statistic title="已处理问题数量" value={this.state.rightAlist.finishQuestion} />
                    </Col>
                    <Col span={5}>
                      <Statistic title="待处理问题数量" value={this.state.rightAlist.waitQuestion} />
                    </Col>
                    <Col className="buttonYs" style={{ display: 'flex', alignItems: 'center', minHeight: 60 }} span={4}>
                      <Button onClick={this.recommendF1} size="large">重新推荐</Button>
                    </Col>
                  </Row>
                  <div className={styles.border}></div>
                  <Form style={{ marginBottom: 20 }} layout="inline">
                    <FormItem>
                      {getFieldDecorator('inputA', { initialValue: '', })(
                        <Search
                          placeholder="请输入关键词"
                          onSearch={value => {
                            this.setState({ query: value, page: 1 }, () => this.knowledgeQuestionList());
                          }}
                          style={{ width: 325 }}
                        />
                      )}
                    </FormItem>
                    <span style={{ float: 'right' }}>
                      <FormItem className="zdyButtonA">
                        <Button onClick={this.batchDelete} type="primary">批量删除</Button>
                      </FormItem>
                      <FormItem className="zdyButtonZ">
                        <Button onClick={this.moveBlacklist} type="primary">批量忽略</Button>
                      </FormItem>
                    </span>
                  </Form>
                  {/*  style={{display: 'flex',justifyContent:'center'}} */}

                  <Spin spinning={this.state.login}>
                    <Table
                      className="zdyTable"
                      rowSelection={rowSelection}
                      onChange={this.pXhandleChange}
                      style={{ padding: '20px 0px 0px 0px' }}
                      columns={columns}
                      dataSource={this.state.similarList} // 数据
                      // onChange={this.handleChange}
                      pagination={{
                        // 分页
                        total: this.state.totala,
                        pageSize: this.state.pageSize, // 显示几条一页
                        current: this.state.page, // 当前页
                        showSizeChanger: true, // 是否显示可以设置几条一页的选项
                        showQuickJumper: true,
                        onChange: this.pageWay,
                        onShowSizeChange: this.onShowSizepageWay,
                      }}
                      rowKey="id"
                    />
                  </Spin>
                </Row>
              )}
            </Card>
            <Modal
              title="选择待推荐问题"
              okText="确认"
              cancelText="取消"
              visible={this.state.rightCol1}
              onOk={this.rightCol1}
              onCancel={this.rightColNo1}
            >
              <Row>
                <Col span={24}>
                  <p>将问题库中满足以下条件的问题进行问题推荐:</p>
                  <Form layout="horizontal">
                    <FormItem label="包含关键词" {...FormItemLayont}>
                      {getFieldDecorator('bkKeyword', {
                        initialValue: '',
                      })(<Input placeholder="多个关键字之间用空格分开"></Input>)}
                    </FormItem>
                    <FormItem label="不含关键词" {...FormItemLayont}>
                      {getFieldDecorator('NoKeyword', {
                        initialValue: '',
                      })(<Input placeholder="多个关键字之间用空格分开"></Input>)}
                    </FormItem>
                    <FormItem label="字数" {...FormItemLayont}>
                      {getFieldDecorator('InputNumber1', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                      )}
                      <span> — </span>
                      {getFieldDecorator('InputNumber2', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                      )}
                    </FormItem>
                    <FormItem label="询问次数" {...FormItemLayont}>
                      {getFieldDecorator('xwcs1', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最小值" style={{ width: 90 }} />
                      )}
                      <span> — </span>
                      {getFieldDecorator('xwcs2', {
                        initialValue: '',
                      })(
                        <InputNumber min={0} max={100} placeholder="最大值" style={{ width: 90 }} />
                      )}
                    </FormItem>
                    <p style={{ color: '#d3d3d3', marginLeft: 30 }}>
                      若不设置任何条件则将对问题库中所有问题进行推荐
                    </p>
                  </Form>
                </Col>
              </Row>
            </Modal>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(ProblemRecommendedList));
